package com.loong.controller;

import com.loong.utils.Constants;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 集中处理方法的调用
 * 以及放回值处理
 */
public class BaseServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String methodStr = req.getParameter(Constants.TAG);
        //如果method没有获取值，我们就跳转到首页
        if (methodStr == null && methodStr.equals("")) {
           methodStr = Constants.INDEX;
        }
        //调用方法，使用反射
        Class clazz = this.getClass();
        //获取方法
        try {
//            Method method = (Method) clazz.getMethod(methodStr, HttpServletRequest.class, HttpServletResponse.class).invoke(this, req, resp);
            Method method = clazz.getMethod(methodStr, HttpServletRequest.class, HttpServletResponse.class);

            //3.执行方法的对象
            Object result = method.invoke(this, req, resp);
            //4.集中处理返回值
            if (result != null) {
                String str = (String) result;
                if(str.startsWith(Constants.FORWARD)){
                    String path = str.substring(str.indexOf(Constants.FLAG)+1);
                    req.getRequestDispatcher(path).forward(req, resp);
                } else if (str.startsWith(Constants.REDIRECT)) {
                    String path = str.substring(str.indexOf(Constants.FLAG)+1);
                    resp.sendRedirect(path);
                }else {
                    resp.getWriter().println(str);
                }
            }

        } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 当method标识符‘没有值’，我们默认 赋index访问每个 servlet的index
     * 默认跳转到程序的首页
     * @param req
     * @param resp
     * @return
     * @throws ServletException
     * @throws IOException
     */

    public String index(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("register");
//        req.getRequestDispatcher("").forward(req, resp);
        return Constants.FORWARD + "index.jsp";
    }
}
